#-------------------------------------------------------------------------------
# Name:        Starfield
# Purpose:
#
# Author:      Pablo
#
# Created:     18/08/2013
# Copyright:   (c) Monxcleyr Productions 2013
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, random, glob, random, config, os, logging
from ..tools import subpixelsurface

class StarField():

  def __init__(self, surface):
    conf = config.Config()
    conf.read(os.path.join("resources/configs/starfield.ini"))
    self.speed = conf.getfloat_tuple('General', 'speed')
    self.millispeed = (self.speed[0]/ 1000.0, self.speed[1]/ 100.0)
    self.layers = []

    # find number of layers
    checking = 1
    count = 1
    while checking:
      if conf.has_section("Layer" + str(count)) == True:
        count += 1
      else:
        checking = 0

    # load the layers
    for i in range(1, count):
      temp = conf.items('Layer' + str(i))
      confdict = dict(temp)
      confdict['sizes'] = conf.getint_list('Layer' + str(i), 'sizes')
      self.layers.append(StarLayer(surface, confdict))
      self.layers[i - 1].setSpeed(self.speed)

  def setFrameRate(self, frametime):

    self.speed = (self.millispeed[0] * frametime, self.millispeed[1] * frametime)

    for layer in self.layers:
      layer.setSpeed(self.speed)


  def changeSpeed(self, speed):

    self.speed = (self.speed[0] + speed[0], self.speed[1] + speed[1])
    for layer in self.layers:
      layer.setSpeed(self.speed)


  def draw(self, surface, common, move=True):

    for layer in self.layers:
      layer.draw(surface, move, common)


class Star():

  def __init__(self, pos, image, color):
    self.pos = pos
    self.imagestr = image
    self.image = pygame.image.load(image).convert_alpha()
    self.image_sub = subpixelsurface.SubPixelSurface(self.image, x_level=4)
    self.color = color
    self.colorlayer = pygame.Surface(self.image.get_size())
    self.colorlayer.fill(self.color)
    self.colorlayer.set_alpha(120)
##    self.image.blit(self.colorlayer, (0,0))

  def draw(self, surf, common):

    if common.settings.quality == 3:
      # Sometimes this fails, unsure why. If it does, draw the star normally.
      try:
        surf.blit(self.image_sub.at(self.pos[0], self.pos[1]), self.pos)
      except:
        logging.warning("Subpixel failed. Star position: %s" % (str(self.pos)))
        surf.blit(self.image, self.pos)
    else:
      surf.blit(self.image, self.pos)

class StarLayer():

  """Star field layer generating class"""

  def __init__(self, surface, config):
    #The screen that this will all be drawn onto
    self.base_surf = surface
    self.populated = False
    self.buffer = 15
    self.stars = []
    self.config = config
    self.config['speed'] = float(self.config['speed']) / 100.0
    self.config['count'] = int(self.config['count'])
    self.config['red'] = float(self.config['red']) / 100.0
    self.config['blue'] = float(self.config['blue']) / 100.0
    self.config['yellow'] = float(self.config['yellow']) / 100.0
    self.config['white'] = float(self.config['white']) / 100.0
    self.colors = {'red': [], 'blue': [], 'yellow': [], 'white': []}


    # load star images
    for color in self.colors:
      for i in range(1,11):
        self.colors[color].append('resources/graphics/starfield/stars/' + color + '/star_' + color + '_' + str(i) + '.png')


    # Make the list of percentages into floats
    temp = []
    for item in self.config['sizes']:
      temp.append(item * .01)

    self.config['sizes'] = temp

    self.sizes = []
    for i in range(0, len(self.config['sizes'])):
      self.sizes += [i] * int(self.config['count'] * self.config['sizes'][i] + .5)

    random.shuffle(self.sizes)




    self.populate()


  def setSpeed(self, speed):
    self.speed = (float(speed[0]) * self.config['speed'], float(speed[1]) * self.config['speed'])

  def populate(self):
    self.x = (-self.buffer, self.base_surf.get_width() + self.buffer)
    self.y = (-self.buffer, self.base_surf.get_height() + self.buffer)

    self.screen_rect = pygame.Rect(-self.buffer, -self.buffer, self.x[1], self.y[1])

    count = 0
    for color in self.colors:
      for i in range(0, int(float(self.config['count']) * self.config[color])):
        tempx = random.randrange(self.x[0], self.x[1])
        tempy = random.randrange(self.y[0], self.y[1])

        tempstar = Star((tempx, tempy), self.colors[color][self.sizes[count]], (255,255,255))
        count += 1
        self.stars.append(tempstar)

  def draw(self, surface, move, common):

    if surface == None:
      surface = self.base_surf

    for star in self.stars:
      if move:
        star.pos = (star.pos[0] + self.speed[0], star.pos[1] + self.speed[1])

      if self.screen_rect.collidepoint(star.pos):
        star.draw(surface, common)
      else:
        testing = True

        if move:
          while testing:
            tempx = random.randrange(self.x[0], self.x[1])
            tempy = random.randrange(self.y[0], self.y[1])
            if self.speed[0] == 0:
              tempx = random.randrange(0, self.x[1] - self.buffer)
            if self.speed[1] == 0:
              tempy = random.randrange(0, self.y[1] + self.buffer)

            if self.base_surf.get_rect().colliderect(pygame.Rect((tempx, tempy), (star.image.get_width(), star.image.get_height()))):
              testing = True
            else:
              star.pos = (tempx, tempy)
  ##            self.stars.append(Star((tempx, tempy), star.imagestr, star.color))
              testing = False




